<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章详情 - StudentHub</title>
    <link rel="shortcut icon" href="/public/favicon.ico" type="image/x-icon">
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>

    <!-- 配置 Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        neutral: {
                            100: '#F8FAFC',
                            200: '#E2E8F0',
                            300: '#CBD5E1',
                            400: '#94A3B8',
                            500: '#64748B',
                            600: '#475569',
                            700: '#334155',
                            800: '#1E293B',
                            900: '#0F172A',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'card-hover': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-balance {
                text-wrap: balance;
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .animate-slide-up {
                animation: slideUp 0.5s ease-out;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>
</head>
<body class="font-inter bg-neutral-100 text-neutral-800">
<!-- 导航栏 -->
<header class="sticky top-0 z-50 bg-white shadow-sm transition-all duration-300" id="navbar">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <a href="/qian/home.html" class="text-primary font-bold text-xl flex items-center">
                <i class="fa fa-graduation-cap mr-2"></i>
                <span>StudentHub</span>
            </a>
        </div>

        <nav class="hidden md:flex items-center space-x-6">
            <a href="/qian/home.html" class="text-primary font-medium">首页</a>
            <!-- 后台管理按钮 -->
            <a href="/hou/index.html" id="adminButton" class="hidden bg-primary text-white px-3 py-1 rounded font-medium hover:bg-primary/90 transition-colors">
                后台管理
            </a>
        </nav>

        <div class="flex items-center space-x-4">
            <!-- Logout Button -->
            <button id="logoutButton" class="text-red-500 hover:text-red-700 transition-colors font-medium hidden md:block">
                退出登录
            </button>

            <div class="relative hidden md:block">
                <label>
                    <input type="text" placeholder="搜索课程、学习资料..." class="pl-10 pr-4 py-2 rounded-full bg-neutral-100 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all w-48 focus:w-64">
                </label>
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400"></i>
            </div>

            <div class="relative group">
                <a href="/qian/user-center.html" class="w-4 h-4 rounded-full overflow-hidden border-2 border-white hover:border-primary transition-all">
                    <!-- Server-side code should replace the src with the user's avatar from session -->
                    <img src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-full h-full object-cover rounded-full" style="width: 40px; height: 40px;">
                </a>

                <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 z-10 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 transform group-hover:translate-y-0 translate-y-2">
                    <a href="user.html" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                        <i class="fa fa-user-o mr-2"></i> 个人主页
                    </a>
                    <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                        <i class="fa fa-cog mr-2"></i> 设置
                    </a>
                    <div class="border-t border-neutral-200 my-1"></div>
                    <a href="#" class="block px-4 py-2 text-sm text-red-500 hover:bg-neutral-100">
                        <i class="fa fa-sign-out mr-2"></i> 退出登录
                    </a>
                </div>
            </div>

            <button class="md:hidden text-neutral-600 hover:text-primary transition-colors">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="container mx-auto px-4 py-8 md:py-12">
    <div id="articleDetail" class="bg-white rounded-xl shadow-sm p-6">
        <!-- Article details will be loaded here -->
        <h1 class="text-3xl font-bold text-neutral-900 mb-4" id="articleTitle"></h1>
        <div class="flex items-center text-neutral-500 text-sm mb-6">
            <img src="" alt="作者头像" class="w-8 h-8 rounded-full mr-2 object-cover" id="authorAvatar">
            <span id="authorName" class="mr-4"></span>
            <span id="publishDate" class="mr-4"></span>
            <span id="tagName" class="bg-primary/10 text-primary px-2 py-0.5 rounded-full text-xs"></span>
        </div>
        <div class="prose" id="articleContent"></div>
        <!-- 评论区 -->
        <div class="mt-10">
            <h2 class="text-lg font-bold mb-4">评论区</h2>
            <div class="mb-4 flex items-start">
                <img id="commentUserAvatar" src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-10 h-10 rounded-full mr-3 object-cover">
                <textarea id="commentInput" rows="3" class="flex-1 rounded-lg border border-neutral-200 p-3 focus:outline-none focus:ring-2 focus:ring-primary/30 resize-none" placeholder="写下你的评论..."></textarea>
                <button id="submitCommentBtn" class="ml-3 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all">发表评论</button>
            </div>
            <div id="commentsList" class="space-y-4">
                <!-- 评论展示区 -->
            </div>
        </div>
    </div>
</main>

<!-- 底部区域 -->
<footer class="bg-white border-t border-neutral-200 mt-12">
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <h3 class="text-lg font-bold text-neutral-900 mb-4">StudentHub</h3>
                <p class="text-neutral-600 text-sm mb-4">探索知识，提升能力，与优秀学子共同成长。</p>
                <div class="flex space-x-4">
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-twitter text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-linkedin text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-weibo text-xl"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="border-t border-neutral-200 mt-8 pt-8 text-center text-neutral-500 text-sm">
            
        </div>
    </div>
</footer>

<!-- 返回顶部按钮 -->
<button id="backToTop" class="fixed bottom-6 right-6 bg-primary/90 hover:bg-primary text-white w-12 h-12 rounded-full flex items-center justify-center shadow-lg transition-all transform translate-y-20 opacity-0">
    <i class="fa fa-angle-up text-xl"></i>
</button>

<script src="/jquery-3.7.1.min.js"></script>
<script>
    $(document).ready(function() {
        // Dynamically set the header avatar from sessionStorage
        const userAvatarName = sessionStorage.getItem('avatarUrl'); // Get the avatar filename from sessionStorage using the key 'avatarUrl'
        const headerAvatar = $('#navbar a.rounded-full img'); // Corrected selector for the avatar image in the header
        const avatarBaseUrl = 'http://localhost:8082/upload/';
        if (userAvatarName && headerAvatar.length > 0) {
            headerAvatar.attr('src', avatarBaseUrl + userAvatarName);
        } else {
            // Optionally set a default avatar if not found in session
            headerAvatar.attr('src', 'http://localhost:8082/upload/default.jpg');
        }

        // Control visibility of Admin button based on user role
        const userRole = sessionStorage.getItem('userRole'); // Assuming user role is stored under this key
        const adminButton = $('#adminButton');

        if (userRole === 'ADMIN') {
            adminButton.removeClass('hidden');
        } else {
            adminButton.addClass('hidden');
        }

        // Function to get URL parameters
        function getUrlParameter(name) {
            name = name.replace(/[[\]]/g, '\\$&');
            const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
            const results = regex.exec(window.location.href);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }

        // Get article ID from URL
        const articleId = getUrlParameter('articleId');

        if (articleId) {
            // Fetch article details
            $.ajax({
                url: `http://localhost:8082/api/articles/detail/${articleId}`,
                method: 'GET',
                success: function(response) {
                    if (response && response.articleId) { // Check if response is not empty and contains articleId
                        const article = response;
                        console.log('Fetched article details:', article);

                        // Populate the page with article details
                        $('#articleTitle').text(article.title);
                        $('#authorAvatar').attr('src', avatarBaseUrl + (article.avatarUrl || 'default.jpg'));
                        $('#authorName').text(article.nickName || '匿名用户');
                        $('#publishDate').text(new Date(article.createdAt).toLocaleDateString()); // Format date
                        $('#tagName').text(article.tagName || '无标签');
                        $('#articleContent').html(article.content); // Use html() to render potential HTML content

                    } else {
                        // Handle case where article is not found or response is empty/incorrect
                        $('#articleDetail').html('<p class="text-center text-red-500">文章详情加载失败或文章不存在。</p>');
                        console.error('Error fetching article details: Invalid response', response);
                    }
                },
                error: function(xhr, status, error) {
                    $('#articleDetail').html('<p class="text-center text-red-500">文章详情加载失败，请稍后重试。</p>');
                    console.error('Error fetching article details:', error);
                }
            });
        } else {
            // Handle case where articleId is not in the URL
            $('#articleDetail').html('<p class="text-center text-red-500">无效的文章ID。</p>');
        }

        // 返回顶部按钮
        window.addEventListener('scroll', function() {
            const backToTopBtn = document.getElementById('backToTop');
            if (window.pageYOffset > 300) {
                backToTopBtn.classList.remove('translate-y-20', 'opacity-0');
                backToTopBtn.classList.add('translate-y-0', 'opacity-100');
            } else {
                backToTopBtn.classList.remove('translate-y-0', 'opacity-100');
                backToTopBtn.classList.add('translate-y-20', 'opacity-0');
            }
        });

        document.getElementById('backToTop').addEventListener('click', function() {
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        });

        // 导航栏滚动效果
        window.addEventListener('scroll', function() {
            const navbar = document.getElementById('navbar');
            if (window.pageYOffset > 50) {
                navbar.classList.add('py-2', 'shadow-md');
                navbar.classList.remove('py-3', 'shadow-sm');
            } else {
                navbar.classList.add('py-3', 'shadow-sm');
                navbar.classList.remove('py-2', 'shadow-md');
            }
        });

        // Add logout functionality for the button
        $('#logoutButton').on('click', function(e) {
            e.preventDefault(); // Prevent default link behavior
            // Clear session storage
            sessionStorage.removeItem('userId');
            sessionStorage.removeItem('username'); // Assuming username is also stored
            sessionStorage.removeItem('avatarUrl');
            sessionStorage.removeItem('userRole'); // Assuming userRole is also stored

            // Redirect to login page
            window.location.href = '/login.html'; // Replace with your login page path
        });

        // 收集所有子评论为一维数组
        function collectAllReplies(comment, replies = []) {
            if (comment.replies && comment.replies.length > 0) {
                comment.replies.forEach(reply => {
                    replies.push(reply);
                    collectAllReplies(reply, replies);
                });
            }
            return replies;
        }

        // 渲染父评论和"查看更多评论"按钮
        function renderComments(comments) {
            const commentsList = $('#commentsList');
            commentsList.empty();
            console.log('评论数据:', comments);
            if (!comments || comments.length === 0) {
                commentsList.html('<p class="text-neutral-400 text-center">暂无评论，快来抢沙发吧~</p>');
                return;
            }
            comments.forEach(parentComment => {
                const user = parentComment.user || {};
                const nickName = user.nickName || parentComment.nickName || '匿名用户';
                const avatarUrl = user.avatarUrl || parentComment.avatarUrl || 'default.jpg';
                const parentDiv = $(`
                    <div class="parent-comment-block">
                        <div class="flex items-start py-3 border-b border-neutral-200 last:border-b-0">
                            <img src="http://localhost:8082/upload/${avatarUrl}" alt="用户头像" class="w-10 h-10 rounded-full mr-3 object-cover">
                            <div class="flex-1">
                                <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-1">
                                    <div class="flex items-center gap-2">
                                        <span class="text-base text-neutral-700 font-medium">${nickName}</span>
                                    </div>
                                    <span class="text-xs text-neutral-400 mt-1 md:mt-0">${new Date(parentComment.createdAt).toLocaleString()}</span>
                                </div>
                                <div class="text-neutral-800 mb-1 leading-relaxed">${parentComment.content}</div>
                                <div class="flex items-center gap-4 mt-1 text-sm text-neutral-400">
                                    <button class="like-btn flex items-center gap-1 hover:text-primary transition-colors"><i class="fa fa-thumbs-o-up"></i>点赞</button>
                                    <button class="reply-btn flex items-center gap-1 hover:text-primary transition-colors" data-comment-id="${parentComment.id}" data-nickname="${nickName}" data-user-id="${parentComment.userId}"><i class="fa fa-reply"></i>回复</button>
                                </div>
                                <div class="reply-box-container"></div>
                                ${parentComment.replies && parentComment.replies.length > 0 ? `<div class="flex justify-center my-1"><button class="show-replies-btn bg-blue-50 text-primary text-xs px-3 py-0.5 rounded-full hover:bg-blue-100 hover:text-blue-700 flex items-center gap-1 transition-all border border-blue-100" data-parent-id="${parentComment.id}" data-expanded="false"><i class='fa fa-comments-o mr-1'></i> 查看更多评论</button></div>` : ''}
                                <div class="replies-container"></div>
                            </div>
                        </div>
                    </div>
                `);
                commentsList.append(parentDiv);
            });
        }

        // 获取并渲染评论
        function fetchComments(articleId) {
            $.ajax({
                url: `http://localhost:8082/api/comments/article/${articleId}`,
                method: 'GET',
                success: function(res) {
                    if (res.code === 200 && Array.isArray(res.data)) {
                        renderComments(res.data);
                    } else {
                        renderComments([]);
                    }
                },
                error: function() {
                    renderComments([]);
                }
            });
        }

        // 发表评论
        $('#submitCommentBtn').on('click', function() {
            const userId = sessionStorage.getItem('userId');
            const content = $('#commentInput').val().trim();
            if (!userId) {
                alert('请先登录后再评论！');
                window.location.href = '/login.html';
                return;
            }
            if (!content) {
                alert('评论内容不能为空！');
                return;
            }
            const articleId = getUrlParameter('articleId');
            // parentId和replyToId此处为null，表示一级评论
            $.ajax({
                url: 'http://localhost:8082/api/comments/add',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    articleId: articleId,
                    userId: userId,
                    content: content,
                    parentId: null,
                    replyToId: null
                }),
                success: function(res) {
                    if (res.code === 200) {
                        $('#commentInput').val('');
                        alert('评论成功！');
                        refreshAllComments();
                    } else {
                        alert('评论失败：' + (res.msg || '未知错误'));
                    }
                },
                error: function() {
                    alert('评论失败，请稍后重试。');
                }
            });
        });

        // 设置评论区头像
        const commentUserAvatar = $('#commentUserAvatar');
        const commentAvatarName = sessionStorage.getItem('avatarUrl');
        if (commentAvatarName && commentUserAvatar.length > 0) {
            commentUserAvatar.attr('src', 'http://localhost:8082/upload/' + commentAvatarName);
        } else {
            commentUserAvatar.attr('src', 'http://localhost:8082/upload/default.jpg');
        }

        // 页面加载时获取评论
        if (articleId) {
            fetchComments(articleId);
        }

        // 回复按钮点击事件（事件委托）
        $('#commentsList').on('click', '.reply-btn', function() {
            // 移除其他已存在的回复框
            $('.reply-input-box').remove();
            const commentId = $(this).data('comment-id');
            const replyToName = $(this).data('nickname');
            const replyToId = $(this).data('user-id');
            const replyBox = $(`
                <div class="reply-input-box mt-2 flex items-start">
                    <img src="${sessionStorage.getItem('avatarUrl') ? 'http://localhost:8082/upload/' + sessionStorage.getItem('avatarUrl') : 'http://localhost:8082/upload/default.jpg'}" class="w-8 h-8 rounded-full mr-2 object-cover">
                    <textarea rows="2" class="flex-1 rounded-lg border border-neutral-200 p-2 focus:outline-none focus:ring-2 focus:ring-primary/30 resize-none" placeholder="回复 ${replyToName}"></textarea>
                    <button class="ml-2 bg-primary hover:bg-primary/90 text-white px-3 py-1 rounded-lg send-reply-btn" data-parent-id="${commentId}" data-reply-to-id="${replyToId}" data-reply-to-name="${replyToName}">发送</button>
                </div>
            `);
            // 插入到当前评论的.reply-box-container中
            $(this).closest('.flex-1').find('.reply-box-container').first().html(replyBox);
        });

        // 发送回复按钮事件（事件委托）
        $('#commentsList').on('click', '.send-reply-btn', function() {
            const userId = sessionStorage.getItem('userId');
            const content = $(this).siblings('textarea').val().trim();
            const parentId = $(this).data('parent-id');
            const replyToId = $(this).data('reply-to-id');
            if (!userId) {
                alert('请先登录后再评论！');
                window.location.href = '/login.html';
                return;
            }
            if (!content) {
                alert('回复内容不能为空！');
                return;
            }
            const articleId = getUrlParameter('articleId');
            $.ajax({
                url: 'http://localhost:8082/api/comments/add',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    articleId: articleId,
                    userId: userId,
                    content: content,
                    parentId: parentId,
                    replyToId: replyToId
                }),
                success: function(res) {
                    if (res.code === 200) {
                        alert('回复成功！');
                        refreshAllComments();
                    } else {
                        alert('回复失败：' + (res.msg || '未知错误'));
                    }
                },
                error: function() {
                    alert('回复失败，请稍后重试。');
                }
            });
        });

        // 查看更多评论按钮事件
        $('#commentsList').on('click', '.show-replies-btn', function() {
            const parentId = $(this).data('parent-id');
            const expanded = $(this).attr('data-expanded') === 'true';
            const parentBlock = $(this).closest('.parent-comment-block');
            const repliesContainer = parentBlock.find('.replies-container');
            if (!expanded) {
                // 展开
                // 找到父评论数据
                const parentComment = findCommentById(window._allComments, parentId);
                if (!parentComment) return;
                const allReplies = collectAllReplies(parentComment, []);
                // 渲染所有子评论
                repliesContainer.empty();
                allReplies.forEach(reply => {
                    const replyUser = reply.user || {};
                    const replyNickName = replyUser.nickName || reply.nickName || '匿名用户';
                    const replyAvatarUrl = replyUser.avatarUrl || reply.avatarUrl || 'default.jpg';
                    // 找到被回复人昵称
                    let replyToName = '';
                    if (reply.replyToUser && reply.replyToUser.nickName) {
                        replyToName = reply.replyToUser.nickName;
                    } else {
                        // 在所有父评论和子评论中查找parentId对应的评论昵称
                        const parentOfReply = findCommentById(window._allComments, reply.parentId);
                        if (parentOfReply) {
                            const parentUser = parentOfReply.user || {};
                            replyToName = parentUser.nickName || parentOfReply.nickName || '';
                        }
                    }
                    const replyContentHtml = replyToName
                        ? `<span class="text-neutral-600 mr-1">${replyNickName}</span> <span class="text-xs text-neutral-400">回复</span> <span class="text-neutral-600 mx-1">${replyToName}</span>：${reply.content}`
                        : `<span class="text-neutral-600 mr-1">${replyNickName}</span>：${reply.content}`;
                    const replyDiv = $(`
                        <div class="flex items-start py-2 ml-12 bg-neutral-50 rounded-lg mb-1">
                            <img src="http://localhost:8082/upload/${replyAvatarUrl}" alt="用户头像" class="w-8 h-8 rounded-full mr-3 object-cover mt-1">
                            <div class="flex-1">
                                <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-1">
                                    <div class="flex items-center gap-2">
                                        <span class="text-sm text-neutral-600">${replyNickName}</span>
                                    </div>
                                    <span class="text-xs text-neutral-400 mt-1 md:mt-0">${new Date(reply.createdAt).toLocaleString()}</span>
                                </div>
                                <div class="text-neutral-800 mb-1 leading-relaxed">${replyContentHtml}</div>
                                <div class="flex items-center gap-4 mt-1 text-xs text-neutral-400">
                                    <button class="like-btn flex items-center gap-1 hover:text-primary transition-colors"><i class="fa fa-thumbs-o-up"></i>点赞</button>
                                    <button class="reply-btn flex items-center gap-1 hover:text-primary transition-colors" data-comment-id="${reply.id}" data-nickname="${replyNickName}" data-user-id="${reply.userId}"><i class="fa fa-reply"></i>回复</button>
                                </div>
                                <div class="reply-box-container"></div>
                            </div>
                        </div>
                    `);
                    repliesContainer.append(replyDiv);
                });
                // 展开后按钮变为"收起评论"
                $(this).attr('data-expanded', 'true').html("<i class='fa fa-angle-up mr-1'></i> 收起评论");
            } else {
                // 收起
                repliesContainer.empty();
                $(this).attr('data-expanded', 'false').html("<i class='fa fa-comments-o mr-1'></i> 查看更多评论");
            }
        });

        // 辅助函数：根据id查找评论
        function findCommentById(comments, id) {
            for (const comment of comments) {
                if (comment.id === id) return comment;
                if (comment.replies && comment.replies.length > 0) {
                    const found = findCommentById(comment.replies, id);
                    if (found) return found;
                }
            }
            return null;
        }

        // 页面加载时保存所有评论数据
        if (articleId) {
            $.ajax({
                url: `http://localhost:8082/api/comments/article/${articleId}`,
                method: 'GET',
                success: function(res) {
                    if (res.code === 200 && Array.isArray(res.data)) {
                        window._allComments = res.data;
                        renderComments(res.data);
                    } else {
                        renderComments([]);
                    }
                },
                error: function() {
                    renderComments([]);
                }
            });
        }

        // 发表评论、回复成功后刷新所有评论
        function refreshAllComments() {
            const articleId = getUrlParameter('articleId');
            if (!articleId) return;
            $.ajax({
                url: `http://localhost:8082/api/comments/article/${articleId}`,
                method: 'GET',
                success: function(res) {
                    if (res.code === 200 && Array.isArray(res.data)) {
                        window._allComments = res.data;
                        renderComments(res.data);
                    } else {
                        renderComments([]);
                    }
                },
                error: function() {
                    renderComments([]);
                }
            });
        }

    });

    // Dynamically set the header avatar on page load (outside of $(document).ready)
    // This part should already be in the header script, keeping for completeness.
    const userAvatarName = sessionStorage.getItem('avatarUrl');
    const headerAvatar = $('#navbar a.rounded-full img');
    const avatarBaseUrl = 'http://localhost:8082/upload/';
    if (userAvatarName && headerAvatar.length > 0) {
        headerAvatar.attr('src', avatarBaseUrl + userAvatarName);
    } else {
        headerAvatar.attr('src', 'http://localhost:8082/upload/default.jpg');
    }

    // Control visibility of Admin button on page load (outside of $(document).ready)
    // This part should already be in the header script, keeping for completeness.
    const userRole = sessionStorage.getItem('userRole');
    const adminButton = $('#adminButton');

    if (userRole === 'ADMIN') {
        adminButton.removeClass('hidden');
    } else {
        adminButton.addClass('hidden');
    }

</script>
</body>
</html> 